/**
 * 
 */
package cc.monggo.demo.thread;


/**
 * @author Administrator
 *
 */
public class ThreadLocalDemo2 {

	ThreadLocal<GlobalCache> cache = new ThreadLocal<GlobalCache>();
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ThreadLocalDemo2 sn = new ThreadLocalDemo2();
		TestClient t1 = new TestClient(sn);
		TestClient t2 = new TestClient(sn);
		t1.start();
		t2.start();
	}
	
	public int add(){
		GlobalCache g = cache.get();
		if(g == null){
			g = new GlobalCache();
		}
		g.add();
		cache.set(g);
		return g.get();
	}
	
	private static class TestClient extends Thread {
		private ThreadLocalDemo2 sn;
		public TestClient(ThreadLocalDemo2 sn) {
			this.sn = sn;
		}

		public void run() {
			for (int i = 0; i < 3; i++) {
				int now = sn.add();
				System.out.println("thread[" + Thread.currentThread().getName()
						+ "] sn[" + now + "]");
			}
		}
	}

}
